import { defineStore } from 'pinia'
import { ref } from 'vue'
//引入接口
import { reqLogin, reqLogout } from '@/api/auth'
import type { LoginFormData, LoginResponseData } from '@/api/auth/type'
import { reqUserInfo } from '@/api/user'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由(常量路由)
import { constantRoute } from '@/router/routes'
import { ElMessage } from 'element-plus'

//创建用户小仓库
const useUserStore = defineStore('User', () => {
  const token = ref<string>(GET_TOKEN() as string)
  const userInfo = ref({
    userId: 0,
    nickname: '',
    avatar: '',
    roles: [],
    perms: [],
  })
  const usereAsyncRoute = ref([])
  async function userLogin(data: LoginFormData) {
    const result: LoginResponseData = await reqLogin(data)
    if (result.code == 20000) {
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = result.data.tokenType + ' ' + result.data.accessToken
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      getUserInfo()
      //能保证当前async函数返回一个成功的promise
      return 'ok'
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }
  async function getUserInfo() {
    const result = await reqUserInfo()
    if (result.code == 20000) {
      userInfo.value = result.data
      return 'ok'
    } else {
      return Promise.reject(new Error(result.msg))
    }
  }
  async function userLogout() {
    await reqLogout()
    REMOVE_TOKEN()
    token.value = ''
    ElMessage({
      message: '成功退出',
      type: 'success',
    })
    window.location.reload()
  }
  return { token, userInfo, userLogout, userLogin, getUserInfo }
})
//对外暴露获取小仓库方法
export default useUserStore
